package com.gao;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * 上传下载文件
 *
 * @author GaoXi
 * @date 2021/8/16 20:58
 */
@Controller
public class FileController {


    @GetMapping("download")
    public ResponseEntity<byte[]> download(HttpSession httpSession) throws IOException {
        ServletContext servletContext = httpSession.getServletContext();
        String filePath = servletContext.getRealPath("kobe.jpg");

        Path path = Paths.get(filePath);
        InputStream inputStream = Files.newInputStream(path);
        byte[] bytes = new byte[inputStream.available()];
        inputStream.read(bytes);
        //创建HttpHeaders对象设置响应头信息
        MultiValueMap<String, String> headers = new HttpHeaders();
        //设置要下载方式以及下载文件的名字
        headers.add("Content-Disposition", "attachment;filename=1.jpg");
        //设置响应状态码
        HttpStatus statusCode = HttpStatus.OK;
        ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(bytes, headers, statusCode);
        return responseEntity;
    }

    @PostMapping("upload")
    public String upload(MultipartFile photo,HttpSession httpSession) throws IOException {
        ServletContext servletContext = httpSession.getServletContext();
        String realPath = servletContext.getRealPath("upload.jpg");
        Files.copy(photo.getInputStream(),Paths.get(realPath));
        return "success";
    }


}
